package com.lingnan.wanxiangxinxun.controller.user;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.lingnan.wanxiangxinxun.entity.dto.UserDTO;
import com.lingnan.wanxiangxinxun.entity.dto.UserLoginOrRegisterDTO;
import com.lingnan.wanxiangxinxun.entity.po.AuthorApplication;
import com.lingnan.wanxiangxinxun.entity.po.User;
import com.lingnan.wanxiangxinxun.entity.vo.common.Result;
import com.lingnan.wanxiangxinxun.service.IUserService;
import com.lingnan.wanxiangxinxun.util.jwtUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author swl
 * @since 2025-03-13
 */
@RestController("UserUserController")
@RequestMapping("/user/user")
public class UserController {

    @Autowired
    private IUserService userService;


    //用户注册
    @PostMapping("/register")
    public Result registerUser(@RequestBody UserLoginOrRegisterDTO uLOrR_DTO) {
        User user = new User();
        user.setCreateTime(LocalDateTime.now());
        BeanUtils.copyProperties(uLOrR_DTO, user);
        try {
            userService.save(user);
        } catch (Exception e) {
            return Result.error("注册失败");
        }
        return Result.success();
    }


    //用户注销
    @DeleteMapping("/deleteUserByIds/{ids}")
    public Result deleteUser(@PathVariable List<Integer> ids) {
        if(ids == null || ids.isEmpty()){
            return Result.error("未选中用户！");
        }

        try{
            boolean deleteRows = userService.removeBatchByIds(ids);
            if(deleteRows){
                return Result.success();
            }else{
                return Result.error("注销失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("未知错误");
        }
    }


    //用户信息修改
    @PutMapping("/updateUser")
    public Result updateUser(@RequestBody UserDTO userDTO) {
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        user.setUpdateTime(LocalDateTime.now());

        try {
            userService.updateById(user);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("修改失败");
        }
        return Result.success();
    }


    //查找--根据id查
    @GetMapping("/getById")
    public Result getUserById(@RequestParam List<Integer> ids) {
        List<User> userList = userService.listByIds(ids);
        return Result.success(userList);
    }


    //查找--用户登录
    @PostMapping("/signIn")
    public Result userLogin(Integer id, String phone, @RequestParam String password) throws JsonProcessingException {
        User user = userService.userSignIn(id, phone, password);
        if (user == null) {
            return Result.error("账号或密码错误");
        }
        if (user.getStatus() == 2) {
            return Result.error("该账户已被封禁");
        }

        //更新登录时间
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        updateWrapper.set("last_login_time", LocalDateTime.now());
        userService.update(updateWrapper);

        user.setPassword("******");
        user.setLastLoginTime(LocalDateTime.now());

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        //返回jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getId());
        claims.put("name" ,user.getName());
        //claims.put("password" ,"******");
        claims.put("phone" ,user.getPhone());
        claims.put("email" ,user.getEmail());
        claims.put("status" ,user.getStatus());
        claims.put("avatar" ,user.getAvatar());
        claims.put("isAuthor" ,user.getIsAuthor());

        //这里手动序列化一下，jwt序列化不了时间格式的值
        claims.put("lastLoginTime", user.getLastLoginTime() != null ? formatter.format(user.getLastLoginTime()) : null);
        claims.put("createTime", user.getCreateTime() != null ? formatter.format(user.getCreateTime()) : null);
        claims.put("updateTime", user.getUpdateTime() != null ? formatter.format(user.getUpdateTime()) : null);

        String UserLoginJwt = jwtUtils.GenerateJwt(claims); //生成令牌,令牌中包含了该员工的部分信息
        return Result.success(UserLoginJwt); //向前端返回令牌
    }



    //新增作者资格申请--用mongodb存储
    @PostMapping("/authorApply")
    public Result authorApply(@RequestBody AuthorApplication authorApplication) {
        return userService.addAuthorApply(authorApplication);
    }
}




